package com.wectrls.common.utils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;

/**
 * @author chenjian
 * @Package
 * @Description:
 * @date 2019/9/17 11:31
 */
@Data
public class ShortMessageUtils {

    //<phoneNum,<code,time>>
    private static HashMap<String, HashMap<String, Long>> map = Maps.newHashMap();

    /**
     * 创建验证码并存储
     *
     * @return 验证码
     */
    public synchronized static String createCode(String phoneNum) {
        //清空超时code
        Long timeMillis = DateUtils.getTimeMillis();
        Set<String> set = map.keySet();
        ArrayList<String> list = Lists.newArrayList();
        for (String phone : set) {
            HashMap<String, Long> hashMap = map.get(phone);
            Set<String> keySet = hashMap.keySet();
            for (String code : keySet) {
                Long aLong = hashMap.get(code);
                if (aLong + (30 * 60 * 1000) < timeMillis) {
                    list.add(phone);
                }
            }
        }
        for (String s : list) {
            map.remove(s);
        }
        Random random = new Random();
        int c = random.nextInt(9) + 1;
        String code = (int) ((Math.random() + c) * 1000) + "";
        HashMap<String, Long> hashMap = Maps.newHashMap();
        hashMap.put(code, timeMillis);
        map.put(phoneNum, hashMap);
        return code;
    }

    /**
     * 校验验证码
     *
     * @param phoneNum 电话号
     * @param code     验证码
     * @param timeOut  有效期
     * @return
     */
    public synchronized static String checkCode(String phoneNum, String code, Long timeOut) {
        timeOut = timeOut < 1L ? 1L : timeOut;
        Long timeMillis = DateUtils.getTimeMillis();
        //查看是否包含phoneNum
        String msg = "noCode";
        boolean containsKey = map.containsKey(phoneNum);
        if (containsKey) {
            HashMap<String, Long> hashMap = map.get(phoneNum);
            boolean containsKey1 = hashMap.containsKey(code);
            if (containsKey1) {
                Long aLong = hashMap.get(code);
                if (aLong + timeOut <= timeMillis) {
                    msg = "timeOut";
                } else {
                    msg = "ok";
                }
            } else {
                msg = "codError";
            }
            map.remove(phoneNum);
        }
        return msg;
    }

   /* public static void main(String[] args) {
        for (int i = 0; i < 10000000; i++) {
            String code = createCode(i + "");
            if (code.length() != 4) {
                System.out.println(code);
            } else {
                if (i % 10000 == 0) {
                    System.out.println(map.size());
                }
            }
        }
    }*/

}
